<template>
  <div class="container">
    <!-- 顶部统计卡片 -->
    <el-card class="attendance-card stat-card">
      <div class="stat-card-content">
        <div>
          <div class="stat-title">未处理</div>
          <div class="stat-value">0</div>
        </div>
        <div>
          <el-button class="stat-btn">打卡范围</el-button>
          <el-button type="primary">设置</el-button>
        </div>
      </div>
    </el-card>

    <!-- 部门筛选卡片 -->
    <el-card class="attendance-card">
      <div class="filter-card">
        <div class="filter-title">部门：</div>
        <el-checkbox-group v-model="checkedDepts" @change="deptChange">
          <el-checkbox v-for="dept in departments" :key="dept.id" :label="dept.name"
            :dataId="dept.id" class="filter-checkbox"></el-checkbox>
        </el-checkbox-group>
      </div>
    </el-card>

    <!-- 考勤表格组件 -->
    <attendance-table :tableData="tableData" :days="days" :total="total" :pageSize="10"
      :currentPage.sync="currentPage" @changeCurPage="changePage" />
  </div>
</template>

<script>
import AttendanceTable from './AttendanceTable.vue';
import { _getDepartmentList } from '@/api/department';
import { _getDeptAttendance } from '@/api/attendance';
export default {
  name: 'Attendance',
  components: { AttendanceTable },
  created() {
    this.getDepartmentList();
    this.getDeptAttendance();
    this.getDaysNow();
  },
  data() {
    return {
      checkedDepts: [], // 存储所选部门，组件存储的是label标签内容，也就是名字
      departments: [], // 存储对象形式 id 和 name
      days: [],
      tableData: null,
      currentPage: 1, // 当前page
      total: null,
      pagesize: 10,
    };
  },
  methods: {
    async deptChange() {
      console.log('this.checkedDepts', this.checkedDepts);
      // 重置数据，防止旧数据残留，导致渲染残留
      this.tableData = [];
      this.total = 0;

      // 检查是否有选中的部门
      if (this.checkedDepts.length === 0) {
        // 如果没有选中部门，显示默认数据或清空表格
        this.getDeptAttendance(); // 调用默认接口
        return;
      }

      const requests = this.checkedDepts
        .map(name => {
          const selectedDept = this.departments.find(value => value.name === name);
          if (!selectedDept) return null;
          return _getDeptAttendance({
            pagesize: 9999, // 假设部门人数不超过 9999，获取全量数据
            deptID: selectedDept.id,
          });
        }) // 过滤掉返回值数组里的null
        .filter(res => res !== null);
      // 等待所有请求完成后，再更新数据
      Promise.all(requests).then(res => {
        this.tableData = res.flatMap(res => res.data.rows || []);
        this.total = res.reduce((prev, cur) => {
          return prev + cur.data.total;
        }, 0); // 此时 totalNum 已正确累加
        console.log('this.total:', this.total);
        console.log('this.tableData', this.tableData);
      });
    },
    async getDepartmentList() {
      const res = await _getDepartmentList();
      console.log('DepartmentList:', res); // 数组包数组
      for (let i of res) {
        this.departments.push({ id: i.id, name: i.name });
      }
      // console.log('departments name:', this.departments);
    },
    // 获取默认考勤数据
    async getDeptAttendance() {
      // 默认展示随机部门列表，不传deptID参数
      const res = await _getDeptAttendance({
        page: 1,
        pagesize: 10,
      });
      this.tableData = res.data.rows;
      this.total = res.data.total;
      // console.log('res:', res);
      console.log('total', this.total);
      console.log(this.tableData);
    },
    getDaysInMonth(year, month) {
      // month 是 1~12 之间的数
      // 创建下一个月的第 0 天，其实就是当前月的最后一天
      return new Date(year, month, 0).getDate();
    },
    getDaysNow() {
      const month = new Date().getMonth();
      const year = new Date().getFullYear();
      const daysNum = this.getDaysInMonth(year, month + 1);
      for (let i = 1; i <= daysNum; i++) {
        const dayOfWeek = new Date(year, month, i).getDay();
        let label = `${month + 1}/${i}`;
        if (dayOfWeek === 6) label = label + '(周六)';
        if (dayOfWeek === 0) label = label + '(周日)';
        this.days.push(label);
      }
      // console.log(month);
    },
    changePage(newPage) {
      this.currentPage = newPage;
    },
  },
};
</script>

<style scoped>
/* .attendance-page {
  padding: 12px;
  background: #f5f6fa;
  min-height: 100vh;
} */
.attendance-card {
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.04);
  margin-bottom: 10px;
}
.stat-card-content {
  display: flex;
  justify-content: space-between;
  align-items: center;
}
.stat-title {
  font-size: 16px;
  font-weight: 500;
}
.stat-value {
  font-size: 28px;
  font-weight: bold;
  margin-top: 8px;
}
.stat-btn {
  margin-right: 10px;
}
.filter-card {
  display: flex;
  justify-content: center;
  align-content: center;
  flex-wrap: nowrap;
  padding: 20px 0;
}
.filter-title {
  white-space: nowrap;
  margin-right: 15px;
  font-size: 14px;
  font-weight: 700;
}
.filter-checkbox {
  margin-right: 16px;
  margin-bottom: 8px;
}
</style> 